package com.zl.learning.lambada;

import java.beans.Introspector;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

public class FnConverter<T> {
    public String getFieldName(Converter<T> fn) {
        return Reflections.fnToFieldName(fn);
    }

    public static <A> FnConverter<A> of(Class<A> clazz) {
        return new FnConverter<A>();
    }

    @FunctionalInterface
    public interface Converter<T> extends Serializable {
        void apply(T t);
    }

    public static class Reflections {
        private static final Pattern GET_PATTERN = Pattern.compile("get[A-Z].*");
        private static final Pattern IS_PATTERN = Pattern.compile("is[A-Z].*");

        public static <T> String fnToFieldName(Converter<T> fn) {
            try {
                Method method = fn.getClass().getDeclaredMethod("writeReplace");
                method.setAccessible(true);
                SerializedLambda invoke = (SerializedLambda) method.invoke(fn);
                // 得到方法名
                String getter = invoke.getImplMethodName();
                // 切割得到字段名
                if (GET_PATTERN.matcher(getter).matches()) {
                    getter = getter.substring(3);
                }
                if (IS_PATTERN.matcher(getter).matches()) {
                    getter = getter.substring(2);
                }
                return Introspector.decapitalize(getter);
            } catch (ReflectiveOperationException e) {
                throw new RuntimeException();
            }
        }
    }

}
